package com.easyhome.dw.timed.task.center.util;

import com.easyhome.common.utils.GrayscaleConstant;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GrayJobUtil {
    public static final String SERVICE_JOB = "job";

    public static final String SUFFIX_SIGN = "(%s)";

    public static final String REGEX_GROUPNAME = "\\((.*?)\\)";

    public static final String REGEX_BRACKET = "(\\(|\\))";

    public static String formatGroup(String groupName) {
        if (StringUtils.isEmpty(groupName)) {
            throw new RuntimeException("groupName is empty!");
        }
        return String.format(SUFFIX_SIGN, groupName);
    }

    public static String formatGroupJob() {
        return formatGroup(SERVICE_JOB);
    }

    public static String formatGroupDefault() {
        return formatGroup(GrayscaleConstant.DEFAULT);
    }

    public static boolean isGrayGroup(String url) {
        return !url.contains(formatGroupDefault());
    }

    public static String getGroupName(String url) {
        if (StringUtils.isEmpty(url)) {
            throw new RuntimeException("url is empty!");
        }
        Pattern patten = Pattern.compile(REGEX_GROUPNAME);
        Matcher matcher = patten.matcher(url);
        String groupName = GrayscaleConstant.DEFAULT;
        if (matcher.find()) {
            groupName = matcher.group();
            groupName = groupName.replaceAll(REGEX_BRACKET, "");
        }
        return groupName;
    }

    public static Set<String> getDistinctGroupNames(String urls) {
        if (StringUtils.isEmpty(urls)) {
            throw new RuntimeException("urls is empty!");
        }
        Pattern patten = Pattern.compile(REGEX_GROUPNAME);
        Matcher matcher = patten.matcher(urls);
        Set<String> groupNames = new HashSet<>();
        while (matcher.find()) {
            groupNames.add(matcher.group().replaceAll(REGEX_BRACKET, ""));
        }
        return groupNames;
    }

    public static String removeGroupName(String url) {
        if (StringUtils.isEmpty(url)) {
            throw new RuntimeException("url is empty!");
        }
        Pattern patten = Pattern.compile(REGEX_GROUPNAME);
        Matcher matcher = patten.matcher(url);
        if (matcher.find()) {
            return url.replaceAll(REGEX_GROUPNAME, "");
        }
        return url;
    }

    public static void main(String[] args) {
        System.out.println(GrayJobUtil.getDistinctGroupNames("ff11334477990011").toString());
    }
}
